【Java基础】Map遍历的5种方式

您所在的位置:网站首页 遍历map stream 【Java基础】Map遍历的5种方式

【Java基础】Map遍历的5种方式

2023-10-14 13:59| 来源: 网络整理| 查看: 265

目录

创建一个集合

方式一:Iterator 迭代器遍历

map.entrySet().iterator();

map.keySet().iterator();

方式二:For Each方式遍历

map.forEach(BiConsumer action)

方式三:获取Collection集合

map.values().forEach()

方式四:增强for遍历map

map.entrySet().for

map.keySet().for

方法五:Stream流遍历

map.entrySet().stream().forEach()

map.keySet().stream().forEach()

💟 创作不易,不妨点赞💚评论❤️收藏💙一下

首先我们需要把map转换为set进行遍历,可使用entrySet和keySet共2种方式进行转换。

每一种情况都可以采用下面的方式进行遍历:

分别是使用迭代器iterator()遍历;增强for循环遍历;forEach+lambda循环遍历,将循环简化;还可以直接通过方法获取Collection集合在进行便利;最后一个就是使用streams流遍历。

创建一个集合 HashMap map = new HashMap(); map.put(1,"ljj"); map.put(2,"zsy"); map.put(3,"sxf"); map.put(4,"wjx"); } 方式一:Iterator 迭代器遍历 map.entrySet().iterator(); map.keySet().iterator(); //Iterator 迭代器遍历 public static void iterator(Map map){ System.out.println("---使用entrySet()迭代器进行遍历map集合---"); Iterator entryIterator = map.entrySet().iterator(); while (entryIterator.hasNext()){ Map.Entry entry = entryIterator.next(); System.out.println(entry.getKey()+":"+entry.getValue()); } System.out.println("---使用KeySet()迭代器进行遍历map集合---"); Iterator keySetIterator = map.keySet().iterator(); while (keySetIterator.hasNext()){ Integer key = keySetIterator.next(); System.out.println(key+":"+map.get(key)); } } 方式二:For Each方式遍历 map.forEach(BiConsumer action) //For Each方式遍历 public static void forEach_map(Map map){ System.out.println("map.forEach(BiConsumer action)方法遍历map"); map.forEach((key,value) -> System.out.println(key+" : "+value)); } 方式三:获取Collection集合 map.values().forEach()

map中的values()方法,通过这个方法可以直接获取Map中存储所有值的Collection集合

//values()方法 public static void Collection_forEach(Map map){ System.out.println("获取map集合的values值集合对象,进行forEach遍历"); //Map中的values()方法,通过这个方法可以直接获取Map中存储所有值的Collection集合 Collection values = map.values(); values.forEach( v -> System.out.println(v)); } 方式四:增强for遍历map map.entrySet().for map.keySet().for public static void for_plus(Map map){ System.out.println("增强for循环,Map.Entry"); for (Map.Entry entry : map.entrySet()){ String value = entry.getValue(); System.out.println(value); } System.out.println("增强for循环,map.keySet"); for (Integer key : map.keySet()){ String value = map.get(key); System.out.println(value); } } 方法五:Stream流遍历 map.entrySet().stream().forEach() map.keySet().stream().forEach() //Stream流遍历 public static void stream_list(Map map){ System.out.println("map.entrySet().stream.forEach()遍历—Stream流遍历"); map.entrySet().stream().forEach((Map.Entry entry) -> { System.out.print(entry.getKey()+":"); System.out.println(entry.getValue()); }); System.out.println("map.keySet().stream.forEach()遍历—Stream流遍历"); map.keySet().stream().forEach(key -> { System.out.println(map.get(key)); }); } 写到最后 四季轮换,已经数不清凋零了多少, 愿我们往后能向心而行,一路招摇胜! 🐋 你的支持认可是我创作的动力 💟 创作不易,不妨点赞💚评论❤️收藏💙一下 😘 感谢大佬们的支持,欢迎各位前来不吝赐教


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3